package org.phoenixframework.common.security.config;

import lombok.AllArgsConstructor;
import org.phoenixframework.common.tools.ResponseUtil;
import org.phoenixframework.common.tools.ResultModel;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2021/5/6 22:04
 * Description:
 */
@AllArgsConstructor
public class TokenLogoutHandler implements LogoutHandler {

    private final TokenManager tokenManager;

    private final RedisTemplate redisTemplate;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader("token");
        if (token != null) {
            String userName = tokenManager.getUsernameByToken(token);
            redisTemplate.delete(userName);
        }
        ResponseUtil.out(response, ResultModel.ok());
    }

}